package com.yao.attendance.server;


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yao.cardrule.CardRule;
import com.yao.constant.AttendanceDevice;

public class TcpServerHandler extends ChannelInboundHandlerAdapter{
	private static Logger logger = LoggerFactory.getLogger(TcpServer.class);

    @Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		if (msg instanceof ByteBuf) {
			ByteBuf buf = (ByteBuf) msg;
			byte[] dst = new byte[10];
			buf.readBytes(dst);
			
			String msgStr = new String(this.bytesToHexString(dst));
			
			//规则1 去卡号后八位，以“，”分割
			String cardNum = CardRule.carNumRuleOne(msgStr);
			
			String command = null;
			//异常数据
			if(null == cardNum){
				command = AttendanceDevice.THREE;
			}else{
				//业务逻辑层，开始处理数据
				logger.info("接收到卡号是:"+cardNum);
				command = AttendanceDevice.ONE;
			}

			byte[] dest = this.hexStringToBytes(command);
			ByteBuf destBuf = ctx.alloc().buffer(dest.length);
			destBuf.writeBytes(dest);
			ctx.channel().writeAndFlush(destBuf);//.addListener(ChannelFutureListener.CLOSE);
			
			ReferenceCountUtil.release(msg);
			
		} else {
			logger.error("error object !");
		}
	}
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception
    {
    	if(ctx != null && ctx.channel() != null && ctx.channel().remoteAddress() != null){
    		logger.info("客户端链接地址:"+ctx.channel().remoteAddress().toString());
    	}else
    	{
    		logger.info("客户端链接地址存在");
    	}
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,
            Throwable cause) throws Exception {
        logger.warn("Unexpected exception from downstream.", cause);
        ctx.close();
    }
 
    /**
     * 
     * @param src
     * @return
     */
    public String bytesToHexString(byte[] src){   
        StringBuilder stringBuilder = new StringBuilder("");   
        if (src == null || src.length <= 0) {   
            return null;   
        }   
        for (int i = 0; i < src.length; i++) {   
            int v = src[i] & 0xFF;   
            String hv = Integer.toHexString(v);   
            if (hv.length() < 2) {   
                stringBuilder.append(0);   
            }   
            stringBuilder.append(hv);   
        }   
        return stringBuilder.toString();   
    }   
    /**  
     * Convert hex string to byte[]  
     * @param hexString the hex string  
     * @return byte[]  
     */  
    public byte[] hexStringToBytes(String hexString) {   
        if (hexString == null || hexString.equals("")) {   
            return null;   
        }   
        hexString = hexString.toUpperCase();   
        int length = hexString.length() / 2;   
        char[] hexChars = hexString.toCharArray();   
        byte[] d = new byte[length];   
        for (int i = 0; i < length; i++) {   
            int pos = i * 2;   
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));   
        }   
        return d;   
    }   
    /**  
     * Convert char to byte  
     * @param c char  
     * @return byte  
     */  
     private byte charToByte(char c) {   
        return (byte) "0123456789ABCDEF".indexOf(c);   
    }
     
//     public static void main(String args[]){
//    	 System.out.println(carNumRuleOne("0c0029cbbc"));
//     }

}
